package cn.tedu.mall.order.controller;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.JsonResult;
import cn.tedu.mall.order.service.IOmsCartService;
import cn.tedu.mall.order.utils.WebConsts;
import cn.tedu.mall.pojo.order.dto.CartAddDTO;
import cn.tedu.mall.pojo.order.dto.CartUpdateDTO;
import cn.tedu.mall.pojo.order.vo.CartStandardVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

@RestController
@RequestMapping("/oms/cart")
@Api(tags = "购物车模块")
public class OmsCartController {
    @Autowired
    private IOmsCartService omsCartService;

    @PostMapping("/add")
    @ApiOperation("新增商品到购物车")
    @PreAuthorize("hasRole('user')") //没有就会返回403
    //@Validated 校验CartAddDTO信息的完整性
    public JsonResult addCart(@Validated CartAddDTO cartAddDTO){
        omsCartService.addCart(cartAddDTO);
        return JsonResult.ok("新增购物车成功");
    }

    //分页查询用户购物车中的商品
    @GetMapping("/list")
    @ApiOperation("分页查询用户购物车中的商品")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页码",name = "page",dataType = "int"),
            @ApiImplicitParam(value = "每页条数",name = "pageSize",dataType = "int")
    })
    @PreAuthorize("hasRole('user')")
    public JsonResult<JsonPage<CartStandardVO>> listCartsByPage(
            @RequestParam(required = false,defaultValue = WebConsts.DEFAULT_PAGE) Integer page,
            @RequestParam(required = false,defaultValue = WebConsts.DEFAULT_PAGE_SIZE) Integer pageSize){

        JsonPage<CartStandardVO> jsonPage = omsCartService.listCarts(page, pageSize);
        return JsonResult.ok(jsonPage);
    }


    //根据id的数组删除商品
    @PostMapping("/delete")
    @ApiOperation("根据id的数组删除商品")
    @ApiImplicitParam(value = "id数组",name = "ids",dataType = "array",required = true)
    @PreAuthorize("hasRole('user')")
    public JsonResult removeCartByIds(Long[] ids){
        omsCartService.removeCart(ids);
        return JsonResult.ok("删除成功");
    }
    //根据用户清空购物车
    @PostMapping("/delete/all")
    @ApiOperation("清空当前用户购物车")
    @PreAuthorize("hasRole('user')")
    public JsonResult removeCartsByUserId(){
        omsCartService.removeAllCarts();
        return JsonResult.ok("清空购物车成功");
    }

    //根据用户修改购物车的数量
    @PostMapping("/update/quantity")
    @ApiOperation("修改购物车的数量")
    @PreAuthorize("hasRole('user')")
    public JsonResult updateQuantity(@Validated  CartUpdateDTO cartUpdateDTO){
        omsCartService.updateQuantity(cartUpdateDTO);
        return JsonResult.ok("商品数量修改成功");
    }
}
